package com.avengers.core;

import com.avengers.core.kit.StringKit;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.render.JsonRender;
import com.jfinal.validate.ValidateException;
import com.jfinal.validate.Validator;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yu.wang
 * @since 2019/6/18 11:44 AM
 **/
public abstract class AbstractAsyncValidator extends Validator {
    private Map<String, String> errorMap = new HashMap<>();
    private Ret errorRet = null;
    private String errorMessage;
    /**
     * 是否带有ajaxFileUpload图片上传功能
     * 解决 IE 不支持 application/json, 在 ajax 上传文件完成后返回 json时 IE 提示下载文件
     */
    private boolean ajaxFileUpload = false;

    public void setAjaxFileUpload(boolean ajaxFileUpload) {
        this.ajaxFileUpload = ajaxFileUpload;
    }

    @Override
    protected void handleError(Controller c) {
        if (ajaxFileUpload) {
            if (null != errorRet) {
                c.renderJson(new JsonRender(errorRet).forIE());
                return;
            }
            //IE浏览图上传图片需特殊处理
            if (StringKit.notBlank(errorMessage)) {
                c.renderJson(new JsonRender(Ret.fail("msg", errorMessage)).forIE());
                return;
            }
            c.renderJson(new JsonRender(Ret.fail().set("msg", errorMap)).forIE());
        } else {
            if (null != errorRet) {
                c.renderJson(errorRet);
                return;
            }
            if (StringKit.notBlank(errorMessage)) {
                c.renderJson(Ret.fail("msg", errorMessage));
                return;
            }
            c.renderJson(Ret.fail().set("msg", errorMap));
        }
    }

    protected void addError(String errorMessage) {
        invalid = true;
        this.errorMessage = errorMessage;
        if (shortCircuit) {
            throw new ValidateException();
        }
    }

    @Override
    protected void addError(String errorKey, String errorMessage) {
        invalid = true;
        errorMap.put(errorKey, errorMessage);
        if (shortCircuit) {
            throw new ValidateException();
        }
    }

    protected void addError(Ret errorRet) {
        invalid = true;
        this.errorRet = errorRet;
        if (shortCircuit) {
            throw new ValidateException();
        }
    }
}
